<template>
  <div class="home-container">
    <!-- 顶部操作区 -->
    <div class="header">
      <div class="action-buttons">
        <el-button type="primary" @click="showAddClientDialog">
          添加下载器
        </el-button>
        <el-button type="primary" @click="showScanPathDialog">
          设置目录
        </el-button>
        <el-button 
          type="primary" 
          @click="startGlobalScan"
          :loading="clientStore.scanProgress.status === 'running'"
        >
          开始对比
        </el-button>
        <el-button 
          type="success" 
          @click="goToScanReport"
        >
          扫描报告
        </el-button>
        <el-button 
          type="warning" 
          @click="showMoveFilesDialog"
        >
          移动文件
        </el-button>

      </div>
    </div>

    <!-- 进度条组件 -->
    <ScanProgress />

    <!-- 下载器列表 -->
    <div class="client-list">
      <el-row :gutter="20">
        <el-col :span="8" v-for="client in clients" :key="client.id">
          <el-card class="client-card">
            <template #header>
              <div class="card-header">
                <span>{{ client.client_type === 'qb' ? 'qBittorrent' : 'Transmission' }}</span>
                <el-dropdown>
                  <el-button type="text">
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="editClient(client)">编辑</el-dropdown-item>
                      <el-dropdown-item @click="deleteClient(client)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
            <div class="client-info">
              <p>地址：{{ client.host }}:{{ client.port }}</p>
              <div class="client-actions">
                <el-button 
                  :type="client.enabled ? 'info' : 'success'"
                  @click="toggleClientStatus(client)"
                >
                  {{ client.enabled ? '禁用' : '启用' }}
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 添加/编辑下载器弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingClient ? '编辑下载器' : '添加下载器'"
      width="500px"
    >
      <el-form :model="clientForm" label-width="120px">
        <el-form-item label="下载器类型">
          <el-select v-model="clientForm.client_type">
            <el-option label="qBittorrent" value="qb" />
            <el-option label="Transmission" value="transmission" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务器地址">
          <el-input v-model="clientForm.host" />
        </el-form-item>
        <el-form-item label="端口">
          <el-input-number v-model="clientForm.port" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="clientForm.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="clientForm.password" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="testConnection">
            测试连接
          </el-button>
          <el-button type="primary" @click="saveClient">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 扫描目录管理对话框 -->
    <el-dialog
      v-model="scanPathDialogVisible"
      title="设置扫描目录"
      width="500px"
    >
      <div class="scan-paths-list">
        <el-table :data="scanPaths" style="width: 100%">
          <el-table-column prop="path" label="目录路径" />
          <el-table-column prop="enabled" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.enabled ? 'success' : 'info'">
                {{ row.enabled ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button 
                :type="row.enabled ? 'info' : 'success'"
                size="small"
                @click="toggleScanPath(row)"
              >
                {{ row.enabled ? '禁用' : '启用' }}
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteScanPath(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="add-scan-path" style="margin-top: 20px;">
        <el-input
          v-model="newScanPath"
          type="textarea"
          :rows="5"
          placeholder="输入扫描目录路径，每行一个路径"
          style="width: 100%;"
        />
        <div style="margin-top: 10px; text-align: right;">
          <el-button
            type="primary"
            @click="addScanPath"
          >
            添加
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 移动文件对话框 -->
    <el-dialog
      v-model="moveFilesDialogVisible"
      title="移动文件"
      width="600px"
    >
      <el-form :model="moveFilesForm" label-width="120px">
        <el-form-item label="CSV报告文件">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            :auto-upload="false"
            :on-change="handleCsvFileChange"
            :limit="1"
            accept=".csv"
          >
            <el-button type="primary">选择CSV文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                请选择从扫描报告页面导出的CSV文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="目标路径">
          <el-input
            v-model="moveFilesForm.targetPath"
            placeholder="请输入目标目录路径"
          />
        </el-form-item>
        
        <el-form-item label="操作预览" v-if="movePreview.length > 0">
          <el-table :data="movePreview" height="200" style="width: 100%">
            <el-table-column prop="originalPath" label="原路径" />
            <el-table-column prop="newPath" label="新路径" />
          </el-table>
        </el-form-item>
        
        <el-form-item label="移动选项">
          <el-checkbox v-model="moveFilesForm.createDirIfNotExists">
            如果目标目录不存在则创建
          </el-checkbox>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="moveFilesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="previewMoveFiles" :disabled="!csvData.length">
            预览
          </el-button>
          <el-button type="warning" @click="executeMoveFiles" :disabled="movePreview.length === 0">
            开始移动
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { More } from '@element-plus/icons-vue'
import { useClientStore } from '../stores/client'
import { Config, ScanPath } from '../types'
import ScanProgress from '../components/ScanProgress.vue'

const router = useRouter()
const clientStore = useClientStore()

// 状态定义
const clients = ref<Config[]>([])
const dialogVisible = ref(false)
const scanPathDialogVisible = ref(false)
const moveFilesDialogVisible = ref(false)
const scanPaths = ref<ScanPath[]>([])
const newScanPath = ref('')
const editingClient = ref<Config | null>(null)
const clientForm = ref({
  client_type: 'qb',
  host: '',
  port: 8080,
  username: '',
  password: '',
  enabled: true
})
const moveFilesForm = ref({
  targetPath: '',
  createDirIfNotExists: true
})
const csvData = ref<Array<{文件名: string, 路径: string, 大小: string, 状态: string}>>([])
const movePreview = ref<Array<{originalPath: string, newPath: string}>>([])
const uploadRef = ref()

// 客户端管理相关方法
const showAddClientDialog = () => {
  editingClient.value = null
  clientForm.value = {
    client_type: 'qb',
    host: '',
    port: 8080,
    username: '',
    password: '',
    enabled: true
  }
  dialogVisible.value = true
}

const testConnection = async () => {
  try {
    const result = await clientStore.testConnection(clientForm.value)
    if (result.success) {
      ElMessage.success('连接测试成功')
    } else {
      ElMessage.error(result.message || '连接测试失败')
    }
  } catch (error) {
    ElMessage.error('连接测试失败')
  }
}

const saveClient = async () => {
  try {
    if (editingClient.value) {
      await clientStore.updateClient(editingClient.value.id, clientForm.value)
      ElMessage.success('更新成功')
    } else {
      await clientStore.addClient(clientForm.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    clients.value = await clientStore.getClients()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const editClient = (client: Config) => {
  editingClient.value = client
  clientForm.value = { ...client }
  dialogVisible.value = true
}

const deleteClient = async (client: Config) => {
  try {
    await ElMessageBox.confirm('确定要删除这个下载器吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await clientStore.deleteClient(client.id)
    ElMessage.success('删除成功')
    clients.value = await clientStore.getClients()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 扫描路径管理相关方法
const showScanPathDialog = async () => {
  try {
    console.log('准备获取扫描目录...')
    scanPaths.value = await clientStore.getScanPaths()
    console.log('获取扫描目录成功:', scanPaths.value)
    scanPathDialogVisible.value = true
  } catch (error) {
    console.error('获取扫描目录失败:', error)
    if (error instanceof Error) {
      ElMessage.error(`获取扫描目录失败: ${error.message}`)
    } else {
      ElMessage.error('获取扫描目录失败')
    }
  }
}

const addScanPath = async () => {
  if (!newScanPath.value.trim()) {
    ElMessage.warning('请输入扫描目录路径')
    return
  }

  try {
    const paths = newScanPath.value.split('\n')
      .map(path => path.trim())
      .filter(path => path)

    if (paths.length === 0) {
      ElMessage.warning('请输入有效的扫描目录路径')
      return
    }

    for (const path of paths) {
      try {
        await clientStore.addScanPath({
          path,
          enabled: true
        })
      } catch (error) {
        console.error(`添加路径失败: ${path}`, error)
        ElMessage.warning(`路径 ${path} 添加失败，可能已存在`)
      }
    }

    scanPaths.value = await clientStore.getScanPaths()
    newScanPath.value = ''
    ElMessage.success('添加扫描目录完成')
  } catch (error) {
    ElMessage.error('添加扫描目录失败')
  }
}

const toggleScanPath = async (path: ScanPath) => {
  try {
    await clientStore.updateScanPath({
      ...path,
      enabled: !path.enabled
    })
    scanPaths.value = await clientStore.getScanPaths()
    ElMessage.success('更新扫描目录状态成功')
  } catch (error) {
    ElMessage.error('更新扫描目录状态失败')
  }
}

const deleteScanPath = async (path: ScanPath) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个扫描目录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await clientStore.deleteScanPath(path.id)
    scanPaths.value = await clientStore.getScanPaths()
    ElMessage.success('删除扫描目录成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除扫描目录失败')
    }
  }
}

// 下载器启用/禁用相关方法
const toggleClientStatus = async (client: Config) => {
  try {
    await clientStore.toggleClient(client.id)
    clients.value = await clientStore.getClients()
    ElMessage.success(client.enabled ? '已禁用下载器' : '已启用下载器')
  } catch (error) {
    ElMessage.error('切换状态失败')
  }
}

// 扫描和清理相关方法
const startGlobalScan = async () => {
  try {
    // 检查是否有启用的下载器
    const configs = await clientStore.getClients()
    const enabledConfigs = configs.filter(config => config.enabled)
    if (enabledConfigs.length === 0) {
      ElMessage.error('请先配置并启用至少一个下载器')
      return
    }

    // 检查是否有启用的扫描路径
    const scanPaths = await clientStore.getScanPaths()
    const enabledPaths = scanPaths.filter(path => path.enabled)
    if (enabledPaths.length === 0) {
      ElMessage.error('请先配置并启用至少一个扫描路径')
      return
    }

    // 立即显示进度窗口
    clientStore.setScanStarted()
    
    ElMessage.info('正在启动全局扫描...')
    
    try {
      const result = await clientStore.startGlobalScan()
      
      if (result.task_id) {
        // 更新任务ID和状态
        clientStore.scanProgress.taskId = result.task_id
        clientStore.updateScanStatus('running', 5, '扫描任务已启动，正在获取进度...')
        
        ElMessage.success('扫描任务已启动，正在获取进度...')
        
        // 开始轮询进度
        try {
          await clientStore.pollScanProgress(result.task_id)
          ElMessage.success('扫描完成！')
        } catch (pollError: any) {
          console.error('轮询进度失败:', pollError)
          ElMessage.error(`扫描进度获取失败: ${pollError.message}`)
          clientStore.updateScanStatus('failed', 0, '扫描进度获取失败', pollError.message)
        }
      } else {
        ElMessage.error('启动扫描失败：未获取到任务ID')
        clientStore.updateScanStatus('failed', 0, '启动扫描失败', '未获取到任务ID')
      }
    } catch (startError: any) {
      console.error('启动扫描失败:', startError)
      ElMessage.error(`启动扫描失败: ${startError.message || '未知错误'}`)
      clientStore.updateScanStatus('failed', 0, '启动扫描失败', startError.message || '未知错误')
    }
    
  } catch (error: any) {
    console.error('全局扫描出错:', error)
    ElMessage.error(`扫描出错: ${error.message || '未知错误'}`)
    clientStore.updateScanStatus('failed', 0, '扫描出错', error.message || '未知错误')
  }
}



// 跳转到扫描报告页面
const goToScanReport = () => {
  // 检查是否有扫描结果
  if (clientStore.scanProgress.status !== 'completed') {
    ElMessage.warning('请先点击"开始对比"按钮完成文件对比后再查看扫描报告')
    return
  }
  
  router.push('/report')
}

// 移动文件相关方法
const showMoveFilesDialog = () => {
  moveFilesDialogVisible.value = true
  moveFilesForm.value.targetPath = ''
  csvData.value = []
  movePreview.value = []
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

const handleCsvFileChange = (uploadFile: any) => {
  if (!uploadFile.raw) return
  
  const reader = new FileReader()
  reader.onload = (e) => {
    const text = e.target?.result as string
    parseCsvData(text)
  }
  reader.readAsText(uploadFile.raw)
}

const parseCsvData = (csvText: string) => {
  const lines = csvText.trim().split('\n')
  if (lines.length < 2) {
    ElMessage.warning('CSV文件格式不正确')
    return
  }
  
  const headers = lines[0].split(',').map(h => h.trim().replace(/"/g, ''))
  const data = []
  
  for (let i = 1; i < lines.length; i++) {
    const values = lines[i].split(',').map(v => v.trim().replace(/"/g, ''))
    if (values.length >= 4) {
      data.push({
        文件名: values[0],
        路径: values[1],
        大小: values[2],
        状态: values[3]
      })
    }
  }
  
  csvData.value = data
  ElMessage.success(`成功读取 ${data.length} 个文件信息`)
}

const previewMoveFiles = async () => {
  if (!csvData.value.length) {
    ElMessage.warning('请先选择CSV文件')
    return
  }
  
  if (!moveFilesForm.value.targetPath.trim()) {
    ElMessage.warning('请输入目标路径')
    return
  }
  
  const targetPath = moveFilesForm.value.targetPath.trim()
  
  try {
    // 检查目标路径是否存在
    if (moveFilesForm.value.createDirIfNotExists) {
      // 这里应该调用后端API检查路径
      // 模拟检查
      ElMessage.info(`将创建目标目录: ${targetPath}`)
    }
    
    // 获取扫描路径
    const paths = await clientStore.getScanPaths()
    const enabledPaths = paths.filter(p => p.enabled).map(p => p.path)
    const preview = []
    
    for (const file of csvData.value) {
      let newPath = file.路径
      
      // 查找匹配的路径前缀
      for (const scanPath of enabledPaths) {
        if (file.路径.startsWith(scanPath)) {
          newPath = file.路径.replace(scanPath, targetPath)
          break
        }
      }
      
      preview.push({
        originalPath: file.路径,
        newPath: newPath
      })
    }
    
    movePreview.value = preview
    ElMessage.success(`预览完成，共 ${preview.length} 个文件需要移动`)
  } catch (error) {
    ElMessage.error('获取扫描路径失败')
    console.error('预览移动文件错误:', error)
  }
}

const executeMoveFiles = async () => {
  if (movePreview.value.length === 0) {
    ElMessage.warning('没有可移动的文件')
    return
  }
  
  try {
    const targetPath = moveFilesForm.value.targetPath.trim()
    
    // 确认操作
    await ElMessageBox.confirm(
      `确定要将 ${movePreview.value.length} 个文件移动到 ${targetPath} 吗？`,
      '确认移动',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    ElMessage.info('正在执行文件移动操作...')
    
    try {
      // 创建文件移动请求数据
      const moveRequests = movePreview.value.map(item => ({
        source: item.originalPath,
        destination: item.newPath
      }))
      
      // 调用后端API执行文件移动（纯粹的文件操作，不涉及数据库）
      const response = await fetch('/api/move-files', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          moves: moveRequests,
          createDirIfNotExists: moveFilesForm.value.createDirIfNotExists
        })
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      
      if (result.success) {
        ElMessage.success(`成功移动 ${result.movedCount || movePreview.value.length} 个文件到 ${targetPath}`)
        moveFilesDialogVisible.value = false
      } else {
        throw new Error(result.error || '文件移动失败')
      }
      
    } catch (error) {
      console.error('文件移动失败:', error)
      ElMessage.error(`文件移动失败: ${error.message}`)
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('文件移动失败')
      console.error('移动文件错误:', error)
    }
  }
}

// 初始化
onMounted(async () => {
  try {
    clients.value = await clientStore.getClients()
  } catch (error) {
    ElMessage.error('获取下载器列表失败')
  }
})
</script>

<style scoped>
.home-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.client-list {
  margin-top: 20px;
}

.client-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.client-info {
  padding: 10px 0;
}

.client-info p {
  margin: 5px 0;
}

.client-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.scan-paths-list {
  max-height: 300px;
  overflow-y: auto;
}

.add-scan-path {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.upload-demo {
  width: 100%;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.move-files-preview {
  margin-top: 20px;
}

.move-files-preview .el-table {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.move-files-actions {
  margin-top: 20px;
  text-align: right;
}

</style>
